import { message, notification } from 'antd';

/**
 *
 * @param params
 * @returns {Promise<Promise<any> | never>}
 */
export function uploadFile(params) {
    toBase64(params);
}
function insertFile(params) {
    params.fileInfo.success({
        url: params.fileUrl,
        meta: {
            id: 'img',
            title: 'xxx',
            alt: 'img'
        }
    });
}

function toBase64(params) {
    if (typeof FileReader === 'undefined') {
        message.warning('当前浏览器不支持FileReader');
    } else {
        try {
            const { file } = params.fileInfo;
            if (!/image\/\w+/.test(file.type)) {
                message.warning('请确保文件为图像类型');
                return false;
            }
            const reader = new FileReader();
            // eslint-disable-next-line func-names
            reader.onload = function() {
                insertFile({ ...params, fileUrl: this.result });
            };
            reader.readAsDataURL(file);
        } catch (e) {
            message.error(`图片转Base64出错啦！${e.toString()}`);
        }
    }
    return '';
}

const codeMessage = {
    200: '服务器成功返回请求的数据。',
    201: '新建或修改数据成功。',
    202: '一个请求已经进入后台排队（异步任务）。',
    204: '删除数据成功。',
    400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
    401: '用户没有权限（令牌、用户名、密码错误）。',
    403: '用户得到授权，但是访问是被禁止的。',
    404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
    406: '请求的格式不可得。',
    410: '请求的资源被永久删除，且不会再得到的。',
    422: '当创建一个对象时，发生一个验证错误。',
    500: '服务器发生错误，请检查服务器。',
    502: '网关错误。',
    503: '服务不可用，服务器暂时过载或维护。',
    504: '网关超时。'
};
const checkStatus = response => {
    if (response.status >= 200 && response.status < 300) {
        return response;
    }
    const errortext = codeMessage[response.status] || response.statusText;
    notification.error({
        message: `请求错误 ${response.status}: ${response.url}`,
        description: errortext
    });
    const error = new Error(errortext);
    error.name = response.status;
    error.response = response;
    throw error;
};

function request(url, option) {
    const defaultOptions = {
        credentials: 'include'
    };
    const newOptions = { ...defaultOptions, ...option };
    if (newOptions.method === 'POST' || newOptions.method === 'PUT' || newOptions.method === 'DELETE') {
        if (!(newOptions.body instanceof FormData)) {
            newOptions.headers = {
                Accept: 'application/json',
                'Content-Type': 'application/json; charset=utf-8',
                ...newOptions.headers
            };
            newOptions.body = JSON.stringify(newOptions.body);
        } else {
            // newOptions.body is FormData
            newOptions.headers = {
                Accept: 'application/json',
                ...newOptions.headers
            };
        }
    }
    return fetch(url, newOptions)
        .then(checkStatus)
        .then(response => {
            // DELETE and 204 do not return data by default
            // using .json will report an error.
            if (newOptions.method === 'DELETE' || response.status === 204) {
                return response.text();
            }
            return response.json();
        });
}

// 上传
export function customUpload({ files, onError, onSuccess, onProgress }) {
    const uploadUrl = '/api/resource/public/oss/v2/produceputpresignurls';
    const { file } = files;
    const params = {
        fileNames: [file.name],
        richText: 1
    };
    const uploadFn = async () => {
        // 获取预签名路径
        const response = await request(uploadUrl, {
            method: 'POST',
            body: params
        });
        // 返回内容
        if (response.data && response.data.length > 0) {
            const { preUrl } = response.data[0];
            const uploadParams = { preUrl, file, onProgress };
            // keyMap[file.name] = keyName;
            // 上传至服务器
            await uploadToServer(uploadParams);
            onSuccess(response, file);
        } else {
            onError(new Error('sign error'));
        }
    };

    try {
        uploadFn();
    } catch (e) {
        onError(e);
    }
}
// 上传至服务器
export function uploadToServer(params) {
    // headers:{'Content-Type':'application/octet-stream'} 很重要！很重要！很重要！
    const defaultOptions = {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/octet-stream'
        }
    };
    defaultOptions.body = params.file;

    // 上传进度
    const progressOptions = {
        file: params.file,
        onProgress: params.onProgress
    };

    return fetch(params.preUrl, defaultOptions, progressOptions)
        .then(checkStatus)
        .then(response => response)
        .catch(e => e);
}
